package com.test.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * restTemplate配置.
 */
@Configuration
public class RestTemplateConfig {

    /**
     * rest连接超时时间（单位为ms）.
     */
    private int connectTimeout = 3000;

    /**
     * 获取响应超时时间（单位为ms）。
     */
    private int readTimeout = 6000;

    /**
     * rest工厂.
     * @return 请求工厂
     */
    @Bean
    public ClientHttpRequestFactory requestFactory() {
        final SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(readTimeout);
        factory.setConnectTimeout(connectTimeout);
        return factory;
    }

    /**
     * rest模板.
     * @param requestFactory 请求工厂
     * @return rest模板
     */
    @Bean
    public RestTemplate restTemplate(final ClientHttpRequestFactory requestFactory) {
        // 添加转换器
        final List<HttpMessageConverter<?>> messageConverters = Arrays.asList(
                new StringHttpMessageConverter(StandardCharsets.UTF_8),
                new FormHttpMessageConverter());
        final RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(requestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        return restTemplate;
    }

    /**
     * json转换类.
     * @return 对象映射器
     */
    @Bean
    public ObjectMapper objectMapper() {
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        return objectMapper;
    }

}
